const { useState, useEffect } = React;
const { Modal, Button, Form, Input, Radio, Switch, Checkbox, message, Select, Col, Row } = antd;

const { Option } = Select;

const SelectIdea = ({prompts, onRowClick}) => {


  const [selectedTags, setSelectedTags] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [prompt, setPrompt] = useState({});
  const [visible, setVisible] = useState(false);
  const [optVisible, setOptVisible] = useState(false);

  useEffect(() => {
    // setSelectedTags([prompt_tag])
  }, [selectedTags]);

  const handleRowClick = (record)=>{
    onRowClick(record)


    setSelectedRowKeys([record.id])
  }

  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange,
  };


  const columns = [
    {
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
      width: 5,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: 'Content',
      dataIndex: 'content',
      key: 'content',
      width: 100,
      render: content => <div> { _.truncate(content, {length:8}) } </div>
    },    
  ];


  const handleSubmit = async (values) => {
    await db.prompts.add(values);

    setVisible(false)
  }

  const handleOptSubmit = async (data) =>{
    prn('data', data)

  }

  const openLink = (url) => {
    window.open(url, '_blank');
  };

  const onFilterClick = (tag) =>{
    setSelectedTags([tag])
  }

  const rendeFilterItem = (item, index) => {
    return (
      <Col span={3}>
        <Button type='link' onClick={()=>{onFilterClick(item)}} >{item}</Button>
      </Col>
    )
  };

  return (
    <div>

    <Row type="flex" justify="start" align="middle" style={{ padding: '3px' }}>
      <Col span={12}>
        <Select mode="multiple"placeholder="Filter by tags"value={selectedTags}
          onChange={setSelectedTags}
          style={{ width: 200 }}
          options={[...new Set(prompts.flatMap(p => p.tags))].map(tag => ({
            value: tag,
            label: tag
          }))}
        />
      </Col>

      {
        [
        '机械飞升传', '小说构思', '小说作家', '作家练笔', '写作基础', '盐选', ' AI小说流', 'writer', '小说创作', 
        '网文编辑', '短篇创作', 'work', 'agent', '人物', '创作模板', '创作要求'
        ].map(rendeFilterItem)
      }
    </Row>

       <Table
        dataSource={prompts.filter(p => 
          selectedTags.length === 0 || 
          selectedTags.every(tag => p.tags? p.tags.includes(tag) : '')
        )}
        rowSelection={rowSelection}
        columns={columns}
        rowKey="id"
        onRow={(record, rowIndex) => ({
          onClick: () => handleRowClick(record),
        })}
      /> 

    </div>
  );
};